package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import service.OrderService;
import service.TOrderService;
import util.JsonTools;
import entities.OrderEntity;

public class OrderServlet extends HttpServlet {

	/**
	 * Constructor of the object.
	 */
	public OrderServlet() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * The doPost method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to
	 * post.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html");

		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");

		PrintWriter out = response.getWriter();
		String userName = request.getParameter("userName").trim();

		String action = request.getParameter("action");
		// 保存订单
		if ("saveOrder".equals(action)) {
			String toAddr = request.getParameter("toAddr").trim();
			String toUser = request.getParameter("toUser").trim();
			String toTime = request.getParameter("toTime").trim();
			String isPaid = request.getParameter("isPaid").trim();
			try {
				// 将数据保存到数据库
				out.print(OrderService.saveOrder(userName, toAddr, toUser,
						toTime, isPaid));
			} catch (SQLException e) {
				e.printStackTrace();
				out.print("failed");
			}
			// 订单历史记录
		} else if ("getOrder".equals(action)) {
			String start = request.getParameter("start");
			String count = request.getParameter("count");
			try {
				List<OrderEntity> orderList = new ArrayList<OrderEntity>();
				orderList = OrderService.getUserOrder(userName, start, count);
				if (orderList.size() != 0) {
					out.print(JsonTools.createJsonString(orderList));
				} else {
					System.out.println("empty啦~~~~~~~~~~~");
					out.print("{\"id\":0}");
				}
				System.out.println(JsonTools.createJsonString(orderList));
			} catch (SQLException e) {
				e.printStackTrace();
				out.print("failed");
			}
			// 订单统计
		} else if ("orderCount".equals(action)) {
			String times = request.getParameter("times");
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date d1 = new Date();
			Date d2 = new Date(d1.getTime() - 2 * 365 * 24 * 60 * 60 * 1000L);
			String to = sdf.format(d1);
			String from = sdf.format(d2);
			if ("month".equals(times)) {
				from = sdf.format(d1.getTime() - 30 * 24 * 60 * 60 * 1000L);
			} else if ("week".equals(times)) {
				from = sdf.format(d1.getTime() - 7 * 24 * 60 * 60 * 1000L);
			}
			System.out.println(userName + "---" + from + "+-----" + to);
			try {
				out.print(OrderService.orderCount(userName, from, to));
			} catch (SQLException e) {
				out.print("failed");
				e.printStackTrace();
			}
		} else if ("saveOrder_tg".equals(action)) {
			String randomNum = (100000 + new Random().nextInt(899999)) + "";
			String toAddr = request.getParameter("toAddr").trim();
			String toUser = request.getParameter("toUser").trim();
			String toTime = request.getParameter("toTime").trim();
			String isPaid = request.getParameter("isPaid").trim();
			try {
				// 将数据保存到数据库
				out.print(TOrderService.saveOrder(userName, toAddr, toUser,
						toTime, isPaid, randomNum) + "," + randomNum);
			} catch (SQLException e) {
				e.printStackTrace();
				out.print("failed");
			}
		}// 商家更新订单状态
		else if ("updateState".equals(action)) {
			String sellerId = request.getParameter("sellerId");
			String orderNo = request.getParameter("orderNo");
			String state = request.getParameter("state");
			String result = "failed";
			try {
				result = OrderService
						.updateOrderState(sellerId, orderNo, state);
			} catch (SQLException e) {
				System.out.println("出错了--更新订单状态失败");
				e.printStackTrace();
			}
			out.print(result);
		}else if("getNewOrder".equals(action)){
			String sellerId = request.getParameter("sellerId");
			String timeBefore = request.getParameter("timeBefore");
			String result = "{'id':0}";
			try {
				result = JsonTools.createJsonString(OrderService
						.findNewOrder(sellerId, timeBefore));
			} catch (SQLException e) {
				System.out.println("出错了--没有新数据");
				e.printStackTrace();
				out.print("{'id':0}");
				return;
			}
			out.print(result);
		}
		out.flush();
		out.close();
	}

	/**
	 * Initialization of the servlet. <br>
	 * 
	 * @throws ServletException
	 *             if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

}
